package cur.tool.common.captcha;

import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.generator.CodeGenerator;
import cn.hutool.core.img.GraphicsUtil;
import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.ThreadLocalRandom;

public class CustomLineCaptcha extends LineCaptcha {
    private File backgroundFile;
    public CustomLineCaptcha(int width, int height, File backgroundFile) {
        super(width, height);
        this.backgroundFile = backgroundFile;
    }

    public CustomLineCaptcha(int width, int height, int codeCount, int lineCount, File backgroundFile) {
        super(width, height, codeCount, lineCount);
        this.backgroundFile = backgroundFile;
    }

    public CustomLineCaptcha(int width, int height, CodeGenerator generator, int interfereCount, File backgroundFile) {
        super(width, height, generator, interfereCount);
        this.backgroundFile = backgroundFile;
    }

    public Image createImage(String code) {
        BufferedImage image = null;
        try {
            image = ImageIO.read(this.backgroundFile);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
//        BufferedImage image = new BufferedImage(this.width, this.height, 1);
        Graphics2D g = GraphicsUtil.createGraphics(image, (Color) ObjectUtil.defaultIfNull(this.background, Color.WHITE));
        this.drawInterfere(g);
        this.drawString(g, code);
        return image;
    }

    private void drawString(Graphics2D g, String code) {
        if (null != this.textAlpha) {
            g.setComposite(this.textAlpha);
        }

        GraphicsUtil.drawStringColourful(g, code, this.font, this.width, this.height);
    }

    private void drawInterfere(Graphics2D g) {
        ThreadLocalRandom random = RandomUtil.getRandom();

        for(int i = 0; i < this.interfereCount; ++i) {
            int xs = random.nextInt(this.width);
            int ys = random.nextInt(this.height);
            int xe = xs + random.nextInt(this.width / 8);
            int ye = ys + random.nextInt(this.height / 8);
            g.setColor(ImgUtil.randomColor(random));
            g.drawLine(xs, ys, xe, ye);
        }

    }
}
